package com.sia.springcloud.protocol;

import com.alibaba.fastjson.JSON;
import com.sia.springcloud.model.Device;
import com.sia.springcloud.model.Point;
import com.sia.springcloud.protocol.IProtocol;
import com.sia.springcloud.protocol.model.BoschDevice;
import com.sia.springcloud.protocol.model.BoschPoint;
import com.sia.springcloud.tool.DBConnectSQL;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Sirius
 * @Date: 2021/10/3 20:05
 * @Description: Modbus数采方法
 **/
@Slf4j
@Data
@Component
public class Bosch implements IProtocol {

    private Long id = 1884608L;



    private static volatile int collectSum = 0;


    private static volatile Map<String, String> tempValueMap = new HashMap<>();


    /**
     * 获取 Value
     * <p>
     * 这里的type是存储在数据库中的，也应该通过pointInfo传递过来
     *
     * @param boschDevice ,boschPoint
     * @return String Value
     * @throws IOException IOException
     * @throws SQLException   SQLException
     */
    public String readValue(BoschDevice boschDevice, BoschPoint boschPoint) throws IOException, SQLException {
        log.info("----------------{}---------------", collectSum++);
        //创建一个数据库线程，读数据库一次
        System.out.println("开始数据库采集线程");
        try {
            DBConnectSQL dbConnectSQL = new DBConnectSQL(boschDevice.getHost(),boschDevice.getPort(), boschDevice.getDbName(), boschDevice.getUsername(),boschDevice.getPassword());
            String titleNames[] = boschDevice.getTitles().split("\t");
            ArrayList titleList = new ArrayList();
            ArrayList result = new ArrayList();
            for (int i = 0; i < titleNames.length; i++) {
                titleList.add(titleNames[i]);
            }
            result.add(titleList);

            //用来存要返回的结果
            Map dbmap = new HashMap();

                String timer=boschPoint.getVarKey().substring(0,11);
                String prog=boschPoint.getVarKey().substring(11,14);
                String sql = "select * from ExtWeldMeasureProt2_V where timerName='" + timer + "' and progNo='"+prog
                        + "' order by dateTime desc";
                ResultSet resultSet = dbConnectSQL.executeQuery(sql);
                int first = 0;
                while (resultSet.next()) {
                    if (first == 0) {
                        ArrayList row = new ArrayList();
                        for (int j = 0; j < titleNames.length; j++) {
                            String value = resultSet.getString(titleNames[j]);
                            row.add(value);
                        }
                        String content = JSON.toJSONString(row);

                        String oldContent = "";
                        if(tempValueMap.containsKey("db_bosch" + "_" + boschPoint.getId()))
                            oldContent = tempValueMap.get("db_bosch" + "_" + boschPoint.getId()).toString();
                        if(!content.equals(oldContent))
                        {
                            tempValueMap.put("db_bosch" + "_" + boschPoint.getId(), content);
                            tempValueMap.put("db_bosch_time" + "_" + boschPoint.getId(), System.currentTimeMillis() + "");
                        }
                        log.info("数据库采集的值 为：{}", content);
                    }
                    first++;
                }
            dbConnectSQL.free();

        } catch (Exception e) {
            log.info("数据库采集失败：{}", e.getMessage());
        }
//        创建一个文件线程，读文件一次，
        System.out.println("开始文件采集线程");
        try{
                String timer=boschPoint.getVarKey().substring(0,11);
                String prog=boschPoint.getVarKey().substring(11,14);
                String varFilePath =boschDevice.getFilePath() + "/" + timer + "/" + "Prog" + prog;
                File file=new File(varFilePath);
                File[] fileList = file.listFiles();
                Integer lastFileIndex = 0;
                if(fileList.length > 0)
                {
                    Long lastmodiey = 0L;
                    for(int fileindex = 0; fileindex < fileList.length; fileindex++){
                        if(fileList[fileindex].lastModified() > lastmodiey)
                        {
                            lastmodiey = fileList[fileindex].lastModified();
                            lastFileIndex = fileindex;
                        }
                    }
                    //得到最新的文件
                    File tagerfile = fileList[lastFileIndex];
                    String content =readFileContent(tagerfile); //file content

                    String oldContent = "";
                    if(tempValueMap.containsKey("file_bosch" + "_" + boschPoint.getId()))
                        oldContent = tempValueMap.get("file_bosch" + "_" + boschPoint.getId()).toString();
                    if(!URLEncoder.encode(content,"utf-8").equals(oldContent))
                    {
                        tempValueMap.put("file_bosch" + "_" + boschPoint.getId(), content);
                        tempValueMap.put("file_bosch_time" + "_" + boschPoint.getId(), System.currentTimeMillis() + "");
                    }
                    log.info("文件采集的值 为：{}", content);
                }


        } catch (Exception e) {
            log.info("数据库采集失败：{}", e.getMessage());
        }

//        判断值 是不是合理可用
        String fileContent = "";
        Long filetime = 0L;
        if(tempValueMap.containsKey("file_bosch" + "_" + boschPoint.getId()))
        {
            fileContent = tempValueMap.get("file_bosch" + "_" + boschPoint.getId()).toString();
            filetime = Long.parseLong(tempValueMap.get("file_bosch_time" + "_" + boschPoint.getId()).toString());
        }


        String dbContent = "";
        Long dbtime = 0L;
        if(tempValueMap.containsKey("db_bosch" + "_" + boschPoint.getId()))
        {
            dbContent = tempValueMap.get("db_bosch" + "_" + boschPoint.getId()).toString();
            dbtime = Long.parseLong(tempValueMap.get("db_bosch_time" + "_" + boschPoint.getId()).toString());
        }

        //说明文件和数据库数据在同相近的时间内
        Map resultMap = new HashMap();
//        if(filetime - dbtime < 1000 || filetime - dbtime > -1000)
//        {
            resultMap.put("dbData", dbContent);
            resultMap.put("fileData", fileContent);
            String result = JSON.toJSONString(resultMap);
            return result;
//        }


//        return "0";
    }

    /**
     * 写入value
     *
     * @param boschDevice
     * @param boschPoint
     * @return
     */
    public boolean writeValue(BoschDevice boschDevice, BoschPoint boschPoint)  {
        return false;
    }


    public String read(Device device, Point point) throws IOException, SQLException {
        BoschDevice boschDevice = BoschDevice.reconvert(device);
        BoschPoint boschPoint = BoschPoint.reconvert(point);

        return readValue(boschDevice, boschPoint);
    }

    public Boolean write(Device device, Point point) throws Exception {
        return  false;
    }



//    读文件内容的方法
    public String readFileContent(File file) {
        //File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }


}
